import { ChangeDetectionStrategy, Component } from '@angular/core';
import { PageHeaderModule } from '@delon/abc/page-header';
import { DelonFormModule, SFSchema, SFUISchema } from '@delon/form';
import { UploadWidgetModule, type SFUploadWidgetSchema } from '@delon/form/widgets/upload';
import { SettingsService, _HttpClient } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Api } from 'src/app/shared/api';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-dashboard-team-upload',
  templateUrl: './team-upload.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [PageHeaderModule, NzSpinModule, DelonFormModule, NzButtonModule, UploadWidgetModule]
})
export class TeamUploadComponent {
  record: any = {};
  data: any = {};
  parentId: string = '0';
  currentTeam: string = '';
  schema: SFSchema = {};
  ui: SFUISchema = {
    '*': {
      spanLabel: 2,
      spanControl: 22
    }
  };
  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    private settingsService: SettingsService
  ) {
    const config = this.modal.getConfig();
    if (config && config.nzData) {
      this.parentId = config.nzData?.parentId;
      this.currentTeam = config.nzData?.currentTeam;
      if (!this.parentId) {
        this.parentId = '0';
      }
    }
    this.schema = {
      properties: {
        file: {
          type: 'string',
          title: '文件',
          ui: {
            headers: { account: this.settingsService.user.name },
            widget: 'upload',
            action: `${Api.BaseNodeApi}/${this.currentTeam}/upload`,
            remove: () => this.fileRemove(),
            data: () => this.getParentId(),
            type: 'drag',
            hint: '单个5TB以内文件，严禁上传公司数据或其他敏感文件'
          } as SFUploadWidgetSchema
        }
      },
      required: ['file']
    };
    // }
  }
  getParentId(): Object {
    return { parentId: this.parentId };
  }
  formValueChange(event: any) {
    if (event && event.value) this.data = event.value;
  }
  beforeUpload(): boolean {
    if (this.data.file) {
      this.msgSrv.warning('只能上传一个文件');
      return false;
    }
    return true;
  }

  close() {
    // this.modal.destroy();
    this.modal.close(true);
  }

  fileRemove(): Observable<boolean> {
    if (this.data && this.data.file && this.data.file.data && this.data.file.data.id) {
      return this.http.delete(`${Api.BaseNodeApi}?id=${this.data.file.data.id}`).pipe(
        map(res => {
          if (res && res.code == ResponseCode.SUCCESS) {
            this.data = {};
            this.msgSrv.success('删除成功!');
            return true;
          }
          return false;
        })
      );
    } else {
      const onSubscribe = (observer: any) => {
        observer.next(true);
      };
      return new Observable<boolean>(onSubscribe);
    }
  }

  save(value: any) {
    console.log(this.data);
    if (this.data && this.data.file && this.data.file.data) {
      let resData = this.data.file.data;
      let entity = { id: resData.id, userAuthority: 0, groupAuthority: 0, otherAuthority: 0 };
      if (value.user) {
        value.user.forEach((element: any) => {
          entity.userAuthority += element;
        });
      } else {
        entity.userAuthority = 7;
      }
      if (value.group) {
        value.group.forEach((element: any) => {
          entity.groupAuthority += element;
        });
      }
      if (value.other) {
        value.other.forEach((element: any) => {
          entity.otherAuthority += element;
        });
      }
      this.http.put(`${Api.BaseNodeApi}/permission`, null, entity).subscribe(res => {
        if (res.code === ResponseCode.SUCCESS) {
          this.data = res.data;
          this.msgSrv.success('成功！');
          this.modal.close(true);
        } else {
          this.msgSrv.error(res.message ? res.message : '失败，未知原因！');
        }
      });
    } else {
      this.msgSrv.warning('请先确保文件已上传成功');
    }
  }
}
